package com.xusheng.cli.tools;

import cn.hutool.core.lang.Dict;
import cn.hutool.http.*;
import com.xusheng.cli.config.SmsSendConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author admin
 */
@Component
@Slf4j
public class SmsUtil {

    @Resource
    private SmsSendConfig smsConfig;

    /**
     * 发送短信验证码
     *
     * @param code     验证码
     * @param expireAt 有效时间
     * @param phone    手机号
     * @return 返回结果
     */
    public Boolean sendSms(String code, int expireAt, String phone) {
        log.info("发送短信验证码,电话号码: {} , 验证码 ：{}", phone, code);
        Dict body = Dict.create()
                .set("mobile", phone)
                .set("templateId", smsConfig.getTemplateId())
                .set("smsSignId", smsConfig.getSmsSignId())
                .set("param", "**code**:" + code + ",**minute**:" + expireAt);
        HttpResponse response = post(smsConfig.getApiUrl(), smsConfig.getAppCode(), body);
        log.info("短信验证码接口请求成功,手机号,{} , 返回内容: {} ", phone, response.body());
        return response.getStatus() == HttpStatus.HTTP_OK;
    }

    private HttpResponse post(String url, String appCode, Dict body) {
        HttpRequest request = HttpUtil.createPost(url)
                .header(Header.AUTHORIZATION, "APPCODE " + appCode)
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8")
                .form(body);
        return request.execute();
    }

}
